﻿using Microsoft.CodeAnalysis.CSharp.Syntax;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Http;
using ThresholdAssistant.Redis;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Constants;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Config = Qiniu.Storage.Config;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 基础业务
    /// </summary>
    public class BaseService : IBaseAutofac
    {
        /// <summary>
        /// HttpClient类
        /// </summary>
        public HttpClientHeaderUtil HttpClientUtil { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public HttpClientHelp HttpClientHelp { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public static readonly HttpClient HttpClient = new HttpClient();

        /// <summary>
        /// Redis缓存客户端
        /// </summary>
        protected static readonly RedisClientUtil _cache = new RedisClientUtil(HardCodeConstant.CsRedisConfigName);

        /// <summary>
        /// http帮助类
        /// </summary>
        protected static Models.HttpHelper HttpHelper = new Models.HttpHelper();

        /// <summary>
        /// 随机数
        /// </summary>
        protected static Random _random = new Random();

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramters"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        protected async Task<ContractResult> GetAsync(string url, Dictionary<string, string> paramters = null, Dictionary<string, string> headers = null)
        {
            return await HttpClientUtil.GetAsync(url, paramters, headers);
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="paramters"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        protected async Task<ContractResult<T>> GetAsync<T>(string url, Dictionary<string, string> paramters = null, Dictionary<string, string> headers = null)
        {
            return await HttpClientUtil.GetAsync<T>(url, paramters, headers);
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        protected async Task<ContractResult> PostAsync<T>(string url, T param, Dictionary<string, string> headers = null)
        {
            return await HttpClientUtil.PostAsync(url, param, headers);
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        protected async Task<T> PostAsync<R, T>(string url, R param, Dictionary<string, string> headers = null)
        {
            return await HttpClientHelp.PostAsync<R, T>(url, param, headers);
        }



        public static readonly string AccessKey = "Wre6sykRM6AH-_iWuGaS80GEQlQDzC6lqhd0DvuR";


        public static readonly string SecretKey = "0CSO2OAao7z0UbKm1z5w457kQdppeeJegDdan1oY";

        // 存储空间名
        public static string Bucket = "cs-fireworks";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static async Task<HttpResult> UploadQiniuAsync(string filePath, string fileName)
        {

            Mac mac = new Mac(AccessKey, SecretKey);
            // 上传文件名
            string key = fileName;

            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;
            // 上传策略的过期时间(单位:秒)
            putPolicy.SetExpires(3600);
            // 文件上传完毕后，在多少天后自动被删除
            putPolicy.DeleteAfterDays = 90;
            // 生成上传token
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Config config = new Config();
            // 设置上传区域
            config.Zone = Qiniu.Storage.Zone.ZONE_CN_South;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U4096K;
            // 表单上传
            FormUploader target = new FormUploader(config);
            return target.UploadFile(filePath, key, token, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="keyList"></param>
        /// <returns></returns>
        public static async Task DeleteQiniuAsync(IEnumerable<string> keyList)
        {
            Config config = new Config();
            config.Zone = Qiniu.Storage.Zone.ZONE_CN_South;
            Mac mac = new Mac(AccessKey, SecretKey);
            BucketManager bucketManager = new BucketManager(mac, config);
            //每个operations的数量不可以超过1000个，如果总数量超过1000，需要分批发送
            List<string> ops = new List<string>();
            foreach (string key in keyList)
            {
                string op = bucketManager.DeleteOp(Bucket, key);
                ops.Add(op);
            }
            BatchResult ret = bucketManager.Batch(ops);
            if (ret.Code / 100 != 2)
            {
                Console.WriteLine("batch error: " + ret.ToString());
            }
            foreach (BatchInfo info in ret.Result)
            {
                if (info.Code == (int)HttpCode.OK)
                {
                    Console.WriteLine("delete success");
                }
                else
                {
                    Console.WriteLine(info.Data.Error);
                }
            }
        }

        ///// <summary>
        ///// 将用户头像转换为默认头像
        ///// </summary>
        ///// <param name="profile"></param>
        ///// <returns></returns>
        //public string ToDefaultProfile(string profile)
        //{
        //    if (string.IsNullOrWhiteSpace(profile))
        //    {
        //        return $"{AppSettingConstant.HostImgUrl}/upfile/profile/default.jpg";
        //    }
        //    return profile;
        //}

    }
}